# -*- coding: utf-8 -*-

'''
2019年6月4日09:35:58
zhouzhongqing
获取ssr账号
'''

import requests
from bs4 import BeautifulSoup
import os
import time
# https://www.youneed.win/free-ssr

'''
{
   "configs" : [
       {
           "remarks" : "",
           "server" : "38.141.44.50",
           "server_port" : 22222,
           "server_udp_port" : 0,
           "password" : "dongtaiwang.com",
           "method" : "aes-256-cfb",
           "protocol" : "origin",
           "protocolparam" : "",
           "obfs" : "plain",
           "obfsparam" : "",
           "group" : "alvin9999",
           "enable" : true,
           "udp_over_tcp" : false
       },

   ],
   "index" : 0,
   "random" : true,
   "sysProxyMode" : 0,
   "shareOverLan" : false,
   "localPort" : 1080,
   "localAuthPassword" : null,
   "dnsServer" : "",
   "reconnectTimes" : 2,
   "randomAlgorithm" : 3,
   "randomInGroup" : false,
   "TTL" : 0,
   "connectTimeout" : 5,
   "proxyRuleMode" : 0,
   "proxyEnable" : false,
   "pacDirectGoProxy" : false,
   "proxyType" : 0,
   "proxyHost" : null,
   "proxyPort" : 0,
   "proxyAuthUser" : null,
   "proxyAuthPass" : null,
   "proxyUserAgent" : null,
   "authUser" : null,
   "authPass" : null,
   "autoBan" : false,
   "sameHostForSameTarget" : false,
   "keepVisitTime" : 180,
   "isHideTips" : true,
   "nodeFeedAutoUpdate" : false,
   "serverSubscribes" : [

   ],
   "token" : {

   },
   "portMap" : {

   }
}
'''


# 写入文件
def write_to_file(file_name, txt):
    '''''
        讲txt文本存入到file_name文件中
    '''
    print("正在存储文件" + str(file_name));
    # 1 打开文件
    # w 如果没有这个文件将创建这个文件
    '''
    'r'：读

    'w'：写

    'a'：追加

    'r+' == r+w（可读可写，文件若不存在就报错(IOError)）

    'w+' == w+r（可读可写，文件若不存在就创建）

    'a+' ==a+r（可追加可写，文件若不存在就创建）
    '''
    f = open(file_name, 'a+', encoding='utf-8');
    # 2 读写文件
    f.write(str(txt));
    # 3 关闭文件
    f.close();


if __name__ == '__main__':
    print("start");
    all_ssr_account = []
    url = "https://www.youneed.win/free-ssr";
    gui_config_txt_path = "F:/software/ShadowsocksR-win-4.9.0/gui-config.json";
    file_prefix = os.getcwd();

    content = requests.get(url);
    # print(content.text);
    # 初始化并制定解析器
    soup = BeautifulSoup(content.text, "lxml");

    table = soup.table;
    # print(table);
    tr_arr = table.find_all("tr");
    for tr in tr_arr:
        # print(tr);
        # print("tr ----------------------");
        td_arr = tr.find_all("td");
        if len(td_arr) >= 7:
            ssr_account = "{\n";
            ssr_account += "\"remarks\" : \"\",\n";
            ssr_account += "\"server\" : \"" + td_arr[1].text + "\",\n";
            ssr_account += "\"server_port\" : " + td_arr[2].text + ",\n";
            ssr_account += "\"server_udp_port\" : 0,\n";
            ssr_account += "\"password\" : \"" + td_arr[3].text + "\",\n";
            ssr_account += "\"method\" : \"" + td_arr[4].text + "\",\n";
            ssr_account += "\"protocol\" : \"" + td_arr[5].text + "\",\n";
            ssr_account += "\"protocolparam\" : \"\",\n";
            ssr_account += "\"obfs\" : \"" + td_arr[6].text + "\",\n";
            ssr_account += "\"obfsparam\" : \"\",\n";
            ssr_account += "\"group\" : \"alvin9999\",\n";
            ssr_account += "\"enable\" : true,\n";
            ssr_account += "\"udp_over_tcp\" : false\n";
            ssr_account += ("}\n");
            all_ssr_account.append(ssr_account);


    # 如果存在先删除，现在是改名
    if os.path.exists(gui_config_txt_path):
        #print(" remove " + gui_config_txt_path)
        rename = gui_config_txt_path+time.strftime("%Y-%m-%d_%H-%M-%S", time.localtime());
        print(" rename " + rename)
        os.rename(gui_config_txt_path, rename)
        #os.remove(gui_config_txt_path);


    os.chdir(file_prefix);
    prefix = open("./prefix");
    prefix_str = "";
    for line in prefix:
        prefix_str += line;
    write_to_file(gui_config_txt_path, prefix_str + "\n");
    all_ssr_account_str = "";
    for index in range(len(all_ssr_account)):
        # print(item + "\n");
        punctuation = "";
        if str(index) != str(len(all_ssr_account) - 1):
            #判断是否要增加逗号
            punctuation = ",";
        all_ssr_account_str += all_ssr_account[index] + punctuation + "\n";


    write_to_file(gui_config_txt_path, all_ssr_account_str + "\n");

    suffix = open("./suffix");
    suffix_str = "";
    for line in suffix:
        suffix_str += line;

    # print(suffix_str);
    write_to_file(gui_config_txt_path, suffix_str + "\n");
    print("end");
    random_input = input("请输入任意字符串结束.");
